package com.yupi.cloudpicturebackend.aop;

import com.yupi.cloudpicturebackend.annotation.AuthCheck;
import com.yupi.cloudpicturebackend.exception.BusinessException;
import com.yupi.cloudpicturebackend.exception.ErrorCode;
import com.yupi.cloudpicturebackend.model.entity.User;
import com.yupi.cloudpicturebackend.model.enums.UserRoleEnum;
import com.yupi.cloudpicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    //切点(在哪些地方需要执行这个代码)
    //校验权限

    /**
     * 执行拦截，权限校验
     *
     * @return
     */
    //@Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //如果不需要权限放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        //必须有权限才会执行以下代码
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要求必须是管理员权限，但是没有管理员权限，拒绝访问
        if (UserRoleEnum.Admin.equals(mustRoleEnum) && !UserRoleEnum.Admin.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();

    }
}
